<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\GoodsTag as GoodsTagModel;

/**
 * 商品标签控制器
 */
class GoodsTag extends Base
{
    /**
     * 根据标签获取商品列表
     */
    public function goodsList()
    {
        $tag_id   = $this->request->post('tag_id', 0);
        $tag_name = $this->request->post('tag_name', '');

        if (empty($tag_id) && empty($tag_name)) {
            return $this->error('请选择标签');
        }

        // 查询标签是否存在
        if (!empty($tag_id)) {
            $tag = GoodsTagModel::find($tag_id);
        } else {
            $tag = GoodsTagModel::where('name', $tag_name)->find();
        }

        if (!$tag) {
            return $this->error('标签不存在');
        }

        // 获取标签关联的商品
        $goods = $tag->goods()
            ->where('status', 1)
            ->order('sort desc, id desc')
            ->paginate($this->limit);

        return $this->success('获取成功', [
            'list'  => $goods->items(),
            'total' => $goods->total(),
            'tag'   => $tag
        ]);
    }

    /**
     * 获取热门标签
     */
    public function hotTags()
    {
        $limit = request()->post('limit', 10);
        $tags  = GoodsTagModel::getHotTags($limit);

        return $this->success('获取成功', $tags);
    }

    /**
     * 获取所有标签
     */
    public function allTags()
    {
        $tags = GoodsTagModel::field('id,name')
            ->order('sort asc, id desc')
            ->select()
            ->toArray();

        return $this->success('获取成功', $tags);
    }
}